<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>IM 群聊</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            min-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            display: flex;
            gap: 20px;
            height: calc(100vh - 100px);
            margin-top: 20px;
        }
        .chat-container {
            flex: 2;
            min-width: 0;
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 10px;
            display: flex;
            flex-direction: column;
            height: 100%;
        }
        .group-list {
            width: 160px;
            min-width: 160px;
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 10px;
            background-color: #f8f9fa;
            display: flex;
            flex-direction: column;
            height: 100%;
        }
        .message-area {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;
            padding-right: 10px;
        }
        .input-area {
            display: flex;
            gap: 10px;
            margin-top: auto;
        }
        textarea {
            flex: 1;
            padding: 8px;
            resize: none;
            height: 60px;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-family: inherit;
            line-height: 1.5;
        }
        .message {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            gap: 8px;
            padding: 10px 10px;
            margin-bottom: 16px;
            max-width: 100%;
            background-color: #e3f2fd;
            border-radius: 3px;
        }
        .message>p {
            margin: 0;
            white-space: pre-line;
        }
        .message-user {
            font-weight: bold;
            min-width: max-content;  /* 确保用户名不会换行 */
        }
        .message-time {
            color: #666;
            font-size: 0.85em;
            margin-left: 8px;
        }
        .message-content {
            word-break: break-word;
            max-width: 100%;
            white-space: pre-wrap;
        }
        .message.other {
            background-color: #f5f5f5;
            margin-right: 20px;
        }
        input[type="text"] {
            flex: 1;
            padding: 5px;
        }
        button {
            padding: 5px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        .group-item {
            padding: 8px 12px;
            margin: 5px 0;
            cursor: pointer;
            border-radius: 5px;
            transition: all 0.2s ease;
            background-color: white;
            border: 1px solid #dee2e6;
        }
        .group-item:hover {
            background-color: #e9ecef;
            border-color: #adb5bd;
        }
        .group-item.active {
            background-color: #007bff;
            color: white;
            border-color: #0056b3;
        }
        .group-list h3 {
            margin: 0 0 10px 0;
            padding-bottom: 10px;
            border-bottom: 1px solid #dee2e6;
        }
        .groups-scroll-container {
            flex: 1;
            overflow-y: auto;
            min-height: 100px;
            max-height: calc(100vh - 250px);
            margin-bottom: 10px;
            scrollbar-width: thin;
            scrollbar-color: #adb5bd #f8f9fa;
        }
        .groups-scroll-container::-webkit-scrollbar {
            width: 6px;
        }
        .groups-scroll-container::-webkit-scrollbar-track {
            background: #f8f9fa;
            border-radius: 3px;
        }
        .groups-scroll-container::-webkit-scrollbar-thumb {
            background-color: #adb5bd;
            border-radius: 3px;
            border: 2px solid #f8f9fa;
        }
        .groups-scroll-container::-webkit-scrollbar-thumb:hover {
            background-color: #6c757d;
        }
        .create-group-container {
            margin-top: auto;
            padding-top: 10px;
            border-top: 1px solid #dee2e6;
        }
        .group-display {
            display: flex;
            align-items: center;
            margin-bottom: 5px;
            padding: 5px;
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            font-family: monospace;
            height: 24px;
        }
        .group-prefix {
            color: #495057;
            padding: 0 2px 0 8px;
        }
        .group-number {
            color: #28a745;
            font-weight: bold;
            padding-left: 2px;
        }
        .create-group-btn {
            width: 100%;
            padding: 8px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.2s;
            font-weight: bold;
        }
        .create-group-btn:hover {
            background-color: #218838;
        }
        .current-user {
            background-color: #f8f9fa;
            padding: 8px 15px;
            border-radius: 5px;
            margin-bottom: 15px;
            border: 1px solid #dee2e6;
            font-size: 14px;
        }
        #currentUserDisplay {
            font-weight: bold;
            color: #007bff;
        }
        .default-group-badge {
            font-size: 12px;
            background-color: #ffc107;
            color: #000;
            padding: 2px 6px;
            border-radius: 10px;
            margin-left: 5px;
            font-weight: normal;
        }
        .create-group-btn:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        .online-users-list {
            width: 120px;
            min-width: 120px;
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 10px;
            background-color: #f8f9fa;
            display: flex;
            flex-direction: column;
            height: 100%;
        }
        .online-users-container {
            flex: 1;
            overflow-y: auto;
            min-height: 100px;
            max-height: calc(100vh - 250px);
            margin-bottom: 10px;
            scrollbar-width: thin;
            scrollbar-color: #adb5bd #f8f9fa;
        }
        .online-user-item {
            padding: 8px 12px;
            margin: 5px 0;
            border-radius: 5px;
            background-color: white;
            border: 1px solid #dee2e6;
        }


        .online-user-item:hover {
            background-color: #f8f9fa;
            border-color: #adb5bd;
        }


        .user-status {
            display: inline-block;
            width: 10px;
            height: 10px;
            border-radius: 50%;
            margin-right: 8px;
            background-color: #28a745; /* 绿色表示在线 */
        }

        .online-users-container {
            flex: 1;
            overflow-y: auto;
            min-height: 100px;
            max-height: calc(100vh - 250px);
            margin-bottom: 10px;
            scrollbar-width: thin;
            scrollbar-color: #adb5bd #f8f9fa;
        }

        .online-users-container::-webkit-scrollbar {
            width: 6px;
        }

        .online-users-container::-webkit-scrollbar-track {
            background: #f8f9fa;
            border-radius: 3px;
        }

        .online-users-container::-webkit-scrollbar-thumb {
            background-color: #adb5bd;
            border-radius: 3px;
            border: 2px solid #f8f9fa;
        }
        /* 未读消息标记 */
        .unread-badge {
            /*display: none;*/
            background-color: #dc3545;
            color: white;
            border-radius: 10px;
            padding: 2px 6px;
            font-size: 12px;
            margin-left: 8px;
        }

        .online-users-header {
            padding: 8px 12px;
            border-bottom: 1px solid #dee2e6;
            margin-bottom: 8px;
        }



        .user-info {
            display: inline-flex;
            flex-direction: column;
        }

        .user-name {
            font-weight: 500;
        }

        .current-user .user-name {
            font-weight: bold;
            color: #007bff;
        }

        .system-message {
            color: #666;
            font-style: italic;
            text-align: center;
            margin: 10px 0;
            padding: 5px;
            background-color: #f8f9fa;
            border-radius: 4px;
        }

    </style>
</head>
<body>
<h1>IM 群聊</h1>
<!-- 添加这行阻止 favicon 请求 -->
<link rel="icon" href="data:,">
<div class="current-user">
    您的用户ID: <span id="currentUserDisplay"></span>
</div>
<div class="login-container" id="loginContainer" style="display: none;">
    <input type="hidden" id="userId">
</div>
<div class="container" id="chatContainer" style="display: none;">
    <div class="group-list">
        <h3>群组列表</h3>
        <div class="groups-scroll-container">
            <div id="groupList"></div>
        </div>
        <div class="create-group-container">
            <div class="group-display">
                <span class="group-prefix">G-</span>
                <span id="newGroupId" class="group-number"></span>
            </div>
            <button onclick="createGroup()" class="create-group-btn">创建新群组</button>
        </div>
    </div>
    <div class="chat-container">
        <h3>当前群组: <span id="currentGroup"></span></h3>
        <div class="message-area" id="messageArea"></div>
        <div class="input-area">
            <textarea id="messageInput" placeholder="输入消息..."></textarea>
            <button onclick="sendMessage()">发送</button>
        </div>
    </div>
    <div class="online-users-list">
        <h3>在线用户</h3>
        <div class="online-users-container" id="onlineUsersList">
        </div>
    </div>
    <!--4.22修改-->
    <div class="online-users-list">
        <h3>离线用户</h3>
        <div class="online-users-container" id="offlineUsersList">
        </div>
    </div>
</div>

<script>
    let ws;
    let currentUserId = '';
    let currentGroupId = '';
    let groupRefreshInterval;
    const messageHistory = JSON.parse(sessionStorage.getItem('messageHistory') || '{}');



    //新增：心跳机制
    let heartbeatInterval;
    let lastMessageTime = Date.now();

    //4.21修改 未读消息
    let unreadMessages = {};

    async function loadHistoryMessages(groupId) {
        try {
            const response = await fetch(`/messages?groupId=${groupId}`);
            const data = await response.json();
            console.log("数据：", data);
            const messageArea = document.getElementById('messageArea');
            messageArea.innerHTML = '';

            data.forEach(msg => {
                const time = new Date(msg.timestamp).toLocaleTimeString();
                const innerHTML = `
                <p style="display: flex; flex-direction: row; align-items: center;">
                    <strong>${msg.fromUser}</strong>
                    <span style="color: #666; font-size: 0.8em;">${time}</span>
                </p>
                <p>${msg.content}</p>`;

                const div = document.createElement('div');
                div.className = `message ${msg.fromUser === currentUserId ? 'self' : 'other'}`;
                div.innerHTML = innerHTML;
                messageArea.appendChild(div);
            });

            messageArea.scrollTop = messageArea.scrollHeight;

        } catch (err) {
            console.error("加载历史消息失败：", err);
        }
    }

    function generateUserId() {
        let userId = sessionStorage.getItem('userId');
        if (!userId) {
            const randomNum = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
            userId = 'u' + randomNum;
            sessionStorage.setItem('userId', userId);
        }
        return userId;
    }

    document.addEventListener('DOMContentLoaded', function() {
        //新增：心跳机制
        stopHeartbeat();


        //实现登录并保存用户信息
        const username = sessionStorage.getItem('username');
        console.log('当前用户名：', username);  // 调试日志，检查是否正确读取到用户名
        if (!username) {
            alert('请先登录');
            window.location.href = "login.html"; // 没有登录信息，跳回登录页
            return;
        }
        document.getElementById('userId').value = username;
        const savedGroupId = sessionStorage.getItem('currentGroupId');
        if (savedGroupId) {
            currentGroupId = savedGroupId;
        }

        //4.21新增2
        // 从sessionStorage恢复未读消息
        const savedUnread = sessionStorage.getItem('unreadMessages');
        if (savedUnread) {
            unreadMessages = JSON.parse(savedUnread);
            // 更新所有群组的未读标记
            Object.keys(unreadMessages).forEach(groupId => {
                if (unreadMessages[groupId] > 0) {
                    updateUnreadCount(groupId);
                }
            });
        }

        login();
    });

    function login() {
        let userId = sessionStorage.getItem('username'); // 优先从 sessionStorage 拿
        if (!userId) {
            // 如果没有，兼容老逻辑（比如从输入框拿）
            userId = document.getElementById('userId').value.trim();
            sessionStorage.setItem('username', userId); // 保存到 sessionStorage，防止丢
        }
        currentUserId = userId;
        document.getElementById('currentUserDisplay').textContent = userId;
        document.getElementById('loginContainer').style.display = 'none';
        document.getElementById('chatContainer').style.display = 'flex';
        connectWebSocket();
        loadGroups();
        groupRefreshInterval = setInterval(loadGroups, 3000);
    }

    //新增：心跳机制
    // 启动心跳
    function startHeartbeat() {
        stopHeartbeat(); // 确保先停止已有的心跳
        heartbeatInterval = setInterval(() => {
            if (ws.readyState === WebSocket.OPEN) {
                const now = Date.now();
                // 检查是否超过心跳间隔没有收到消息
                if (now - lastMessageTime > 30000) {
                    console.warn('No message received for too long, reconnecting...');
                    ws.close();
                    return;
                }
                ws.send('HEARTBEAT');
            }
        }, 1000); // 每1秒发送一次心跳
    }

    //新增：心跳机制
    // 停止心跳
    function stopHeartbeat() {
        if (heartbeatInterval) {
            clearInterval(heartbeatInterval);
            heartbeatInterval = null;
        }
    }

    function connectWebSocket() {
        // 获取当前页面的协议（http: 或 https:）
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        // 获取当前页面的主机名和端口
        const host = window.location.hostname;
        // netty 使用的端口
        const wsPort = '8080';

        // 构建 WebSocket URL
        const wsUrl = `${protocol}//${host}:${wsPort}/ws`;

        ws = new WebSocket(wsUrl);

        ws.onopen = () => {
            console.log('WebSocket连接已建立');
            //新增：心跳机制
            // 启动心跳
            startHeartbeat();

            // 自动加入默认群组并设置为当前群组
            currentGroupId = 'G00001';
            joinGroup('G00001');
        };

        ws.onmessage = (event) => {
            //新增：心跳机制
            lastMessageTime = Date.now(); // 更新最后消息时间
            // 检查是否是心跳消息
            if (event.data === 'HEARTBEAT') {
                console.log('Received heartbeat');
                return; // 心跳消息不进行JSON解析
            }

            // 尝试解析JSON消息
            /*try {
                const message = JSON.parse(event.data);
                // 处理消息...
                if (message.fromUser === 'system' && message.content.startsWith('ERROR:')) {
                    if (message.content === 'ERROR:MAX_GROUPS_REACHED') {
                        alert('已达到最大群组数量限制（10个）');
                    }
                    return;
                }

                //处理在线用户列表消息（4.21新增）
                if (message.fromUser === 'system' && message.content.startsWith('ONLINE_USERS:')) {
                    const users = message.content.substring('ONLINE_USERS:'.length).split(',');
                    updateOnlineUsers(users);
                    return;
                }

                displayMessage(message);

            }*/
            //4.22修改
            try {
                const message = JSON.parse(event.data);

                // 处理系统消息
                if (message.fromUser === 'system') {
                    if (message.content.startsWith('ERROR:')) {
                        if (message.content === 'ERROR:MAX_GROUPS_REACHED') {
                            alert('已达到最大群组数量限制（10个）');
                        }
                    } else if (message.content.startsWith('ONLINE_USERS:')) {
                        const users = message.content.substring('ONLINE_USERS:'.length).split(',');
                        console.log(users);
                        updateOnlineUsers(users);
                    } else if (message.content.startsWith('OFFLINE_USERS:')) {
                        const users = message.content.substring('OFFLINE_USERS:'.length).split(',');
                        updateOfflineUsers(users);
                    }
                } else {
                    // 处理普通消息
                    displayMessage(message);
                }
            } catch (error) {
                console.error('Error parsing message:', error);
            }
        };

        ws.onclose = () => {
            console.log('WebSocket连接已关闭');

            //关闭心跳
            stopHeartbeat();

            //4.22新增
            clearInterval(heartbeatInterval); // 停止心跳
            clearInterval(groupRefreshInterval); // 停止群组刷新

            sessionStorage.setItem('messageHistory', JSON.stringify(messageHistory));
            sessionStorage.setItem('currentGroupId', currentGroupId);

            // 显示连接已断开提示 4.21新增
            const messageArea = document.getElementById('messageArea');
            const div = document.createElement('div');
            div.className = 'system-message';
            div.textContent = '连接已断开，正在尝试重新连接...';
            messageArea.appendChild(div);
            messageArea.scrollTop = messageArea.scrollHeight;


            //setTimeout(connectWebSocket, 5000);
            setTimeout(connectWebSocket, 1000);
        };

    }


    async function loadGroups() {
        try {
            const response = await fetch(`/api/groups?user=${currentUserId}`);
            const response2=await fetch(`/api/groups/counts?user=${currentUserId}`);
            let response3;
            let users;

            if(!currentGroupId =="G00001")
            {
                console.log("进入：a"+currentGroupId+"b");
                response3=await fetch(`/api/groups/users?groupId=${currentGroupId}`);
            }
            const groups = await response.json();
            const count=await response2.json();
            if(!currentGroupId =="G00001")
            {users =await response3.json();}
            const groupList = document.getElementById('groupList');
            const onlineUsersList = document.getElementById('onlineUsersList');
            groupList.innerHTML = '';
            let a=0;

            groups.forEach(groupId => {
                const div = document.createElement('div');
                if (groupId === 'G00001') {
                    div.innerHTML = `${groupId} <span class="default-group-badge">默认群组</span>`;
                } else {
                    div.textContent = groupId;
                }
                div.className = `group-item ${groupId === currentGroupId ? 'active' : ''}`;
                if (a<count){
                    div.style.backgroundColor='#317fce';
                }
                else{

                }
                a++;

                div.onclick = () => switchGroup(groupId);
                groupList.appendChild(div);
            });

            if (!currentGroupId) {
                switchGroup('G00001');
            }
            if(!currentGroupId=="G00001"){
            users.forEach(userId => {
                const userItem = document.createElement('div');
                userItem.className = `online-user-item ${userId === currentUserId ? 'current-user' : ''}`;
                div.className = `group-item ${groupId === currentGroupId ? 'active' : ''}`;
                // 用户信息
                const userInfo = document.createElement('div');
                userInfo.className = 'user-info';
                const userName = document.createElement('span');
                userName.className = 'user-name';
                userName.textContent = userId;
                if (userId === currentUserId) {
                    userName.textContent += ' (我)';
                    userItem.classList.add('current-user');
                }

                userInfo.appendChild(userName);
                userItem.appendChild(userInfo);
                onlineUsersList.appendChild(userItem);
            });
            }
        } catch (error) {
            console.error('加载群组失败:', error);
        }
    }

    async function joinGroup(groupId) {
        currentGroupId = groupId;
        sessionStorage.setItem('currentGroupId', groupId);
        document.getElementById('currentGroup').textContent = groupId;
        document.querySelectorAll('.group-item').forEach(item => {
            item.classList.remove('active');
            if (item.textContent === groupId) {
                item.classList.add('active');
            }
        });
        document.getElementById('messageArea').innerHTML = '';

        await loadHistoryMessages(groupId); // 加载历史消息

        const joinMessage = {
            fromUser: currentUserId,
            content: 'JOIN_GROUP:' + groupId,
            groupId: groupId,
            timestamp: Date.now()
        };
        if (ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify(joinMessage));
        }
    }

    function generateGroupId() {
        return Math.floor(Math.random() * 100000).toString().padStart(5, '0');
    }

    function createGroup() {
        const existingGroups = document.querySelectorAll('.group-item').length;
        if (existingGroups >= 10) {
            alert('已达到最大群组数量限制（10个）');
            return;
        }

        const groupNumber = generateGroupId();
        const fullGroupId = 'G' + groupNumber;
        joinGroup(fullGroupId);
        loadGroups();
    }

    function sendMessage() {
        if (!currentGroupId) {
            alert('请先选择群组');
            return;
        }

        const messageInput = document.getElementById('messageInput');
        const content = messageInput.value.trim();

        if (!content) {
            return;
        }

        const message = {
            fromUser: currentUserId,
            content: content,
            groupId: currentGroupId,
            timestamp: Date.now()
        };

        ws.send(JSON.stringify(message));
        messageInput.value = '';

    }

    /*async function switchGroup(groupId) {
        console.log(`Switching to group ${groupId}`);
        if (currentGroupId) {
            const messageArea = document.getElementById('messageArea');
            messageHistory[currentGroupId] = messageArea.innerHTML;
        }

        currentGroupId = groupId;

        document.querySelectorAll('.group-item').forEach(item => {
            item.classList.remove('active');
            if (item.textContent.includes(groupId)) {
                item.classList.add('active');

                // 清除未读消息标记 4.20
                const badge = item.querySelector('.unread-badge');
                if (badge) {
                    badge.textContent = '0';
                    badge.style.display = 'none'; // 隐藏未读标记
                }
            }
        });

        const messageArea = document.getElementById('messageArea');
        messageArea.innerHTML = messageHistory[groupId] || '';
        messageArea.scrollTop = messageArea.scrollHeight;

        document.getElementById('currentGroup').textContent = groupId;

        await loadHistoryMessages(groupId); // 加载历史消息

        const joinMessage = {
            fromUser: currentUserId,
            content: 'JOIN_GROUP:' + groupId,
            groupId: groupId,
            timestamp: Date.now()
        };

        if (ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify(joinMessage));
        }

        //4.21新增2
        // 清除该群组的未读计数
        if (unreadMessages[groupId]) {
            unreadMessages[groupId] = 0;
            sessionStorage.setItem('unreadMessages', JSON.stringify(unreadMessages));
            updateUnreadCount(groupId);
        }
    }*/

    async function switchGroup(groupId) {
        console.log(`Switching to group ${groupId}`);

        // 保存当前群组的消息历史
        if (currentGroupId) {
            const messageArea = document.getElementById('messageArea');
            messageHistory[currentGroupId] = messageArea.innerHTML;
        }

        // 清除该群组的未读计数
        if (unreadMessages[groupId] && unreadMessages[groupId] > 0) {
            delete unreadMessages[groupId];
            sessionStorage.setItem('unreadMessages', JSON.stringify(unreadMessages));

            // 移除未读标记
            document.querySelectorAll('.group-item').forEach(item => {
                if (item.textContent.includes(groupId)) {
                    const badge = item.querySelector('.unread-badge');
                    if (badge) {
                        badge.remove();
                    }
                }
            });
        }

        // 更新当前群组ID
        currentGroupId = groupId;
        sessionStorage.setItem('currentGroupId', groupId);

        // 更新UI状态
        document.querySelectorAll('.group-item').forEach(item => {
            item.classList.remove('active');
            if (item.textContent.includes(groupId)) {
                item.classList.add('active');
            }
        });

        // 显示群组标题
        document.getElementById('currentGroup').textContent = groupId;

        // 加载消息历史
        const messageArea = document.getElementById('messageArea');
        messageArea.innerHTML = messageHistory[groupId] || '';

        // 加载历史消息
        await loadHistoryMessages(groupId);

        // 自动滚动到底部
        messageArea.scrollTop = messageArea.scrollHeight;

        // 发送加入群组消息
        const joinMessage = {
            fromUser: currentUserId,
            content: 'JOIN_GROUP:' + groupId,
            groupId: groupId,
            timestamp: Date.now()
        };

        if (ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify(joinMessage));
        } else {
            console.warn('WebSocket not ready, cannot send join message');
        }
    }

    function displayMessage(message) {
        const time = new Date(message.timestamp).toLocaleTimeString();
        const innerHTML = `
                <p style="display: flex; flex-direction: row; align-items: center;">
                    <strong>${message.fromUser}</strong>
                    <span style="color: #666; font-size: 0.8em;">${time}</span>
                </p>
                <p>${message.content}</p>`;

        //// 如果是其他群组的消息，增加未读计数
        /*if (message.groupId !== currentGroupId) {
            if (!messageHistory[message.groupId]) {
                messageHistory[message.groupId] = '';
            }
            const tempDiv = document.createElement('div');
            tempDiv.className = `message ${message.fromUser === currentUserId ? 'self' : 'other'}`;
            tempDiv.innerHTML = innerHTML;
            messageHistory[message.groupId] += tempDiv.outerHTML;
            sessionStorage.setItem('messageHistory', JSON.stringify(messageHistory));

            // 新增：添加未读消息标记
            updateUnreadCount(message.groupId);
            return;*/
        //4.21修改 未读消息2
        if (message.groupId !== currentGroupId) {
            if (!unreadMessages[message.groupId]) {
                unreadMessages[message.groupId] = 0;
            }
            unreadMessages[message.groupId]++;
            updateUnreadCount(message.groupId);

            // 保存到sessionStorage
            sessionStorage.setItem('unreadMessages', JSON.stringify(unreadMessages));


        }
        const messageArea = document.getElementById('messageArea');
        const div = document.createElement('div');
        div.className = `message ${message.fromUser === currentUserId ? 'self' : 'other'}`;
        div.innerHTML = innerHTML;

        messageArea.appendChild(div);
        messageArea.scrollTop = messageArea.scrollHeight;

        messageHistory[currentGroupId] = messageArea.innerHTML;
        sessionStorage.setItem('messageHistory', JSON.stringify(messageHistory));

    }



    document.getElementById('messageInput').addEventListener('keypress', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });

    window.onbeforeunload = function() {
        if (groupRefreshInterval) {
            clearInterval(groupRefreshInterval);
        }
    };


    function updateOnlineUsers(users) {
        const onlineUsersList = document.getElementById('onlineUsersList');
        onlineUsersList.innerHTML = '';

        if(users.toString()===''){
            // 没有在线用户时显示提示
            const header = document.createElement('div');
            header.className = 'online-users-header';
            header.innerHTML = `<strong>在线用户(0)</strong>`;
            onlineUsersList.appendChild(header);
        }
        else{
            // 添加标题和计数

            const header = document.createElement('div');
            header.className = 'online-users-header';
            header.innerHTML = `<strong>在线用户 (${users.length})</strong>`;
            onlineUsersList.appendChild(header);

            // 排序用户列表(当前用户置顶)
            const sortedUsers = [...users].sort((a, b) => {
                if (a === currentUserId) return -1;
                if (b === currentUserId) return 1;
                return a.localeCompare(b);
            });
            console.log(("排序后："+sortedUsers));
            sortedUsers.forEach(userId => {
                const userItem = document.createElement('div');
                //userItem.className = 'online-user-item';
                //4.21修改
                userItem.className = `online-user-item ${userId === currentUserId ? 'current-user' : ''}`;

// 状态图标
                const statusIcon = document.createElement('span');
                statusIcon.className = 'user-status';
                statusIcon.style.backgroundColor = '#28a745'; // 绿色表示在线
                // 用户信息
                const userInfo = document.createElement('div');
                userInfo.className = 'user-info';

                const userName = document.createElement('span');
                userName.className = 'user-name';
                userName.textContent = userId;

                if (userId === currentUserId) {
                    userName.textContent += ' (我)';
                    userItem.classList.add('current-user');
                }

                userInfo.appendChild(userName);
                userItem.appendChild(statusIcon);
                userItem.appendChild(userInfo);
                onlineUsersList.appendChild(userItem);
                // 添加点击事件可以扩展私聊功能
                userItem.addEventListener('click', () => {
                    // 这里可以扩展私聊功能
                    console.log('Start private chat with:', userId);
                });
            });
        }
    }

    //4.22新增 离线用户列表
    function updateOfflineUsers(users) {
        console.log('Received offline users:', users); // 调试日志
        const offlineUsersList = document.getElementById('offlineUsersList');
        offlineUsersList.innerHTML = '';

        //4.23修改
        // 添加标题和计数 - 只有当有用户时才显示
        console.log(users.length);
        console.log(users.toString());
        if(users.toString()===''){
            // 没有离线用户时显示提示
            const header = document.createElement('div');
            header.className = 'online-users-header';
            header.innerHTML = `<strong>离线用户(0)</strong>`;
            offlineUsersList.appendChild(header);
        }
        else{
            const header = document.createElement('div');
            header.className = 'online-users-header';
            header.innerHTML = `<strong>离线用户(${users.length})</strong>`;
            offlineUsersList.appendChild(header);

            // 排序用户列表(当前用户置顶)
            const sortedUsers = [...users].sort((a, b) => {
                if (a === currentUserId) return -1;
                if (b === currentUserId) return 1;
                return a.localeCompare(b);
            });

            sortedUsers.forEach(userId => {
                const userItem = document.createElement('div');
                userItem.className = `online-user-item ${userId === currentUserId ? 'current-user' : ''}`;

                // 状态图标
                const statusIcon = document.createElement('span');
                statusIcon.className = 'user-status';
                statusIcon.style.backgroundColor = '#A0A0A0'; // 灰色表示离线

                // 用户信息
                const userInfo = document.createElement('div');
                userInfo.className = 'user-info';

                const userName = document.createElement('span');
                userName.className = 'user-name';
                userName.textContent = userId;

                if (userId === currentUserId) {
                    userName.textContent += ' (我)';
                    userItem.classList.add('current-user');
                }

                userInfo.appendChild(userName);
                userItem.appendChild(statusIcon);
                userItem.appendChild(userInfo);
                offlineUsersList.appendChild(userItem);
            });
        }
    }

    // 在窗口关闭时清理资源
    window.addEventListener('beforeunload', () => {
        stopHeartbeat();
        if (groupRefreshInterval) {
            clearInterval(groupRefreshInterval);
        }
        if (ws && ws.readyState === WebSocket.OPEN) {
            ws.close();
        }
    });


    //新增：未读信息提示
    /*function updateUnreadCount(groupId) {
        const groupItems = document.querySelectorAll('.group-item');
        groupItems.forEach(item => {
            if (item.textContent.includes(groupId)) {
                // 查找或创建未读标记
                let badge = item.querySelector('.unread-badge');
                if (!badge) {
                    badge = document.createElement('span');
                    badge.className = 'unread-badge';
                    item.appendChild(badge);
                }
                // 更新未读计数
                /*const currentCount = parseInt(badge.textContent) || 0;
                badge.textContent = currentCount + 1;
                badge.style.display = 'inline-block';*/
    //4.21修改2
    /*badge.textContent = unreadMessages[groupId] || '0';
    badge.style.display = 'inline-block';

    console.log(`Updated unread count for group ${groupId}: ${badge.textContent}`);
}
});
}*/
    function updateUnreadCount(groupId) {
        const groupItems = document.querySelectorAll('.group-item');
        groupItems.forEach(item => {
            if (item.textContent.includes(groupId)) {
                let badge = item.querySelector('.unread-badge');

                // 只有存在未读消息时才创建/更新标记
                if (unreadMessages[groupId] > 0) {
                    if (!badge) {
                        badge = document.createElement('span');
                        badge.className = 'unread-badge';
                        item.appendChild(badge);
                    }
                    badge.textContent = unreadMessages[groupId];
                    badge.style.display = 'inline-block';
                } else if (badge) {
                    // 如果没有未读消息但有标记，则移除
                    badge.remove();
                }
            }
        });

    }
</script>
</body>
</html> 